import { getToken, setToken, removeToken } from '@/utils/auth.js'
import { loginAPI, getUserBaseInfoAPI, getEmployeeBaseInfoAPI } from '@/api/index.js'

const state = {
  token: getToken(), // 在cookie中获取token
  userInfo: {}
}

const mutations = {
  // 修改token
  // mutations用来修改state
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = undefined
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 储存用户信息
  saveUserInfo(state, userInfo) {
    state.userInfo = { ...userInfo }
  },
  // 清除用户信息
  clearUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async login(context, loginForm) {
    const token = await loginAPI(loginForm)

    // 储存token
    context.commit('setToken', token)
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('clearUserInfo')
  },
  // 获取用户信息
  async getUserInfo(context) {
    // 获取用户信息
    const userInfo = await getUserBaseInfoAPI()
    const employeeInfo = await getEmployeeBaseInfoAPI(userInfo.userId)
    // console.log(employeeInfo)
    // 合并并储存用户基本信息
    context.commit('saveUserInfo', { ...userInfo, ...employeeInfo })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
